/*
 * @Author: liuzehai
 * @Date: 2021-05-08 13:06:29
 * @LastEditTime: 2021-05-11 16:35:33
 * @LastEditors: liuzehai
 * @FilePath: /Card-to-payh5/src/store/index.js
 * @Description: 由liuzehai创建！
 */
import Vue from "vue";
import Vuex from "vuex";
import { login, getUserInfo } from "@/api";

Vue.use(Vuex);

const getDefaultState = () => {
  return {
    token: localStorage.getItem("token"),
    userInfo: {},
    hasLogin: false,
  };
};

export default new Vuex.Store({
  state: getDefaultState(),
  mutations: {
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState());
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_LOGIN_STATUS: (state, status) => {
      state.hasLogin = status;
    },
  },
  actions: {
    // user login
    login({ commit }, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          username: username.trim(),
          password: password,
        })
          .then(async (response) => {
            const res = response.data.data;
            const token = "bearer " + res.accessToken;
            commit("SET_TOKEN", token);
            commit("SET_LOGIN_STATUS", true);
            localStorage.setItem("token", token);
            sessionStorage.setItem("userId", res.userId); //存储用户id
            sessionStorage.setItem("tenantId", res.tenantId); //存储租户id
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // get user info
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo({
          permission: true,
        })
          .then(async (response) => {
            let res = response.data.data;
            sessionStorage.setItem("userInfo", JSON.stringify(res));
            sessionStorage.setItem("deptId", res.deptId); //存储部门id
            commit("SET_USER_INFO", res); //把 用户信息 保存到vuex中
            commit("SET_LOGIN_STATUS", true);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // user logout
    logout({ commit, state, dispatch }) {
      return new Promise((resolve, reject) => {
        commit("RESET_STATE");
        commit("SET_TOKEN", null);
        commit("SET_LOGIN_STATUS", false);
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("tenantId");
        sessionStorage.removeItem("userId");
        sessionStorage.removeItem("deptId");
        localStorage.removeItem("token");
        resolve();
      });
    },
  },
  modules: {},
});
